package com.icebergteam.warfacewidget.news.ui;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.icebergteam.warfacewidget.AppManager;
import com.icebergteam.warfacewidget.WidgetProvider;
import com.icebergteam.warfacewidget.core.LogManager;
import com.icebergteam.warfacewidget.core.asynctaskmanager.IHandleMessage;
import com.icebergteam.warfacewidget.core.asynctaskmanager.IProgressTracker;
import com.icebergteam.warfacewidget.core.asynctaskmanager.Task;
import com.icebergteam.warfacewidget.core.asynctaskmanager.TaskProgress;
import com.icebergteam.warfacewidget.core.connection.NetworkException;
import com.icebergteam.warfacewidget.core.connection.NetworkManager;
import com.icebergteam.warfacewidget.core.utils.FileLoadingListener;
import com.icebergteam.warfacewidget.core.utils.TimeDateUtils;
import com.icebergteam.warfacewidget.core.utils.ViewUtils;
import com.icebergteam.warfacewidget.data.sql.NewsTable;
import com.icebergteam.warfacewidget.news.data.NewsItem;
import com.icebergteam.warfacewidget.ui.ProgressDialogView;
import com.icebergteam.warfacewidget.ui.TwitchTVVideoPlayerActivity;
import com.icebergteam.warfacewidget.ui.YouTubeVideoPlayerActivity;
import com.icebergteam.warfacewidget.R;
import android.support.v4.app.Fragment;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.webkit.WebStorage;

public class NewsPage extends Fragment implements IProgressTracker, IHandleMessage{
	
	private JIFace iface = new JIFace();
		
	public static String className = NewsPage.class.getCanonicalName();
	//
	public static final String ARG_NUMBER_PAGE = String.format(
			"%s.ARG_NUMBER_PAGE", className);
	public static String ITEM_INTENT_KEY = String.format("%s.ITEM_INTENT_KEY",
			className);
	private com.icebergteam.warfacewidget.news.data.NewsItem item;

	private int pageNumber;
	// Views
	FrameLayout mainView;
		// RSS
	ScrollView	rssView;
	ImageView	rssHeaderImage;
	TextView	rssTitle;
	TextView	rssDate;
	TextView	rssText;
		// Progress
	ProgressDialogView progressView;
		// News from site
	WebView			newsFromSite;	
	NewsPageState newsPageState;
	ImageButton updateButton;
	
	HtmlDownloadTask htmlDownloadTasks;
	
	static NewsActivity parentActivity;
	
	public static final String FILE_ANDROID_ASSET_NEWS_404_HTML = "file:///android_asset/news/404.html";
	
	public void setNewsItem(NewsItem item){
		this.item = item;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		pageNumber = getArguments().getInt(NewsPage.ARG_NUMBER_PAGE);
		
		if(AppManager.getNewsSettings().isDisplayNewsFromSite()){
			this.newsPageState = NewsPageState.ENPS_NORMALL;
		}
		else{
			this.newsPageState = NewsPageState.ENPS_RSS;
		}

		if (savedInstanceState != null) {
			item = (com.icebergteam.warfacewidget.news.data.NewsItem) savedInstanceState
					.get(NewsPage.ITEM_INTENT_KEY);
		} 
		
	}
	public void update(){
		runOnUi(new Runnable() {
				@Override
				public void run() {
					new HtmlDownloadTask(true, true, null, NewsPage.this, NewsPage.this).execute();
				}
		});
	}
	
	@Override
	public void onDestroy() {
		LogManager.LogV(className, LogManager.getExecuteMethodName(), pageNumber);
		super.onDestroy();	
		switch(this.newsPageState){
			case ENPS_RSS:
				break;
			case ENPS_NORMALL:
				htmlDownloadTasks.cancel(true);
				htmlDownloadTasks.abort();	
				newsFromSite.stopLoading();
				break;
		default:
			break;
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putParcelable(NewsPage.ITEM_INTENT_KEY, this.item);
		super.onSaveInstanceState(outState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		this.mainView = (FrameLayout)inflater.inflate(R.layout.news_page, container, false);
		this.progressView = new ProgressDialogView(mainView, inflater, container, savedInstanceState);

		setViews();
		setValues();
			
		return mainView;
	}
	
	public int getPageNumber() {
		return pageNumber;
	}

	private void setViews() {
		LogManager.LogV(className, LogManager.getExecuteMethodName());
		this.rssView		= (ScrollView)	mainView.findViewById(R.id.news_page_rss_view);
		this.progressView.hide();
		setState(newsPageState);
		
		switch(this.newsPageState){
			case ENPS_RSS:
				
				this.rssHeaderImage	= (ImageView)	mainView.findViewById(R.id.news_page_rss_image);
				this.rssTitle		= (TextView)	mainView.findViewById(R.id.news_page_rss_title_text);
				this.rssDate		= (TextView)	mainView.findViewById(R.id.news_page_rss_date);
				this.rssText		= (TextView)	mainView.findViewById(R.id.news_page_rss_text);
				break;
				
			case ENPS_NORMALL:
				
				this.newsFromSite = new WebView(this.getActivity());
				this.newsFromSite.setVisibility(View.GONE);
				
				NetworkManager.setupPolicy();
				WebSettings localWebSettings = this.newsFromSite.getSettings();
		        localWebSettings.setJavaScriptEnabled(true);
		        this.newsFromSite.addJavascriptInterface(iface, "droid");
		        localWebSettings.setAllowFileAccess(true);
		        localWebSettings.setAppCacheEnabled(true);
		        localWebSettings.setDomStorageEnabled(true);
		        localWebSettings.setAppCacheMaxSize(1024*1024*8);
		        localWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
		  		        
		        String appCachePath = this.getActivity().getApplicationContext().getCacheDir().getAbsolutePath();
		        this.newsFromSite.getSettings().setAppCachePath(appCachePath);

		        this.newsFromSite.setBackgroundColor(0);
		        this.newsFromSite.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
		        this.newsFromSite.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY );
		        
		        this.newsFromSite.setWebViewClient(new WebViewClient() {
			          public void onPageFinished(WebView paramAnonymousWebView, String paramAnonymousString){
			        	  try {
				        	  NewsPage.this.progressView.hide();
				        	  NewsPage.this.newsFromSite.setVisibility(View.VISIBLE);
				        	  NewsPage.this.updateButton.setVisibility(View.VISIBLE);
				        	  
				        	  LogManager.LogVA(className, paramAnonymousString);
				        	  if(!paramAnonymousString.equals(FILE_ANDROID_ASSET_NEWS_404_HTML) && parentActivity != null){
				        			parentActivity.setReadNews(getPageNumber());
									
				        	  }
			        	  } 
			        	  catch (Exception e) {
								LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
			        	  }
			          }
			
			          public void onPageStarted(WebView paramAnonymousWebView, String paramAnonymousString, Bitmap paramAnonymousBitmap) {
			        	  NewsPage.this.updateButton.setVisibility(View.GONE);
			        	  NewsPage.this.progressView.show();
			        	  
			          }
			
			          public boolean shouldOverrideUrlLoading(WebView webView, String url)  {
				            if (!url.equals("file:///android_asset/webkit/")) {
				         				            	
				            	if(YouTubeVideoPlayerActivity.initByUrl(url, NewsPage.this.getActivity())){
				            		LogManager.LogV(className, LogManager.getExecuteMethodName() + " check url - youtube", url);
				            	}
				            	else if(TwitchTVVideoPlayerActivity.initByUrl(url,  NewsPage.this.getActivity())){
				            		LogManager.LogV(className, LogManager.getExecuteMethodName() + " check url - twitch", url);
				            	}
				            	else if(url != null){
				            		Intent intent = new Intent("android.intent.action.VIEW");
									intent.setData(Uri.parse(url));
									NewsPage.this.getActivity().startActivity(Intent.createChooser(intent, getString(R.string.news_page_choose)));
								}
					           
				            }
				            return true;
			          }
		        });
		        
		        this.newsFromSite.setWebChromeClient(new WebChromeClient(){
		              public void onProgressChanged(WebView paramAnonymousWebView, int progress){
		            	  NewsPage.this.progressView.setProgress(progress);
		              }
		              @Override
		              public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota,
		                           WebStorage.QuotaUpdater quotaUpdater){
		                    quotaUpdater.updateQuota(spaceNeeded * 2);
		              }
	            });
		     
				this.mainView.addView(this.newsFromSite);
				this.updateButton = (ImageButton) this.mainView.findViewById(R.id.news_page_update_button);
				this.updateButton.bringToFront();
				this.updateButton.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						NewsPage.this.update();
					}
				});
					
				htmlDownloadTasks = new HtmlDownloadTask(true, false, null, this,this);
				break;
		default:
			break;
		}
	}
	
	private void setValues() {
		try {
			LogManager.LogV(className, LogManager.getExecuteMethodName());
			switch(this.newsPageState){
				case ENPS_RSS:
				
					ViewUtils.downloadFile(item.getLink(), NewsTable.TABLE_NAME, item.getImgSrc()/*"https://pp.vk.me/c405623/g42970549/e_7f0ccc99.jpg"*/, WidgetProvider.RSSITEMLOGO_PATH, ViewUtils.TYPE_VIDEO, AppManager.getNewsSettings().isRSSThumbnails(), new FileLoadingListener() {
						@Override
						public void onLoadingFailed(String uri) {
						}
					
						@Override
						public void onLoadingComplete(final String uri) {
							NewsPage.this.getActivity().runOnUiThread(new Runnable() {
								@Override
								public void run() {
									try {
										Bitmap firstBitmap = ViewUtils.scaleImage(uri, 110);
									    final TransitionDrawable td = new TransitionDrawable(new Drawable[] {
								           new ColorDrawable(android.R.color.transparent),
								           new BitmapDrawable(NewsPage.this.getResources(), firstBitmap)
								        });
								        rssHeaderImage.setImageDrawable(td);
									    td.startTransition(2000);
									} catch (Exception e) {
										LogManager.LogEA(className, "if download = false and database empty for its news, link is invalid and shown default image", e.getLocalizedMessage() , uri);
										
									}
								}
							});
							LogManager.LogVA(className, uri);
						}
					});
					rssTitle.setText(item.getTitle());
					rssDate.setText(TimeDateUtils.getDateStringFromNormalTimestamp(item.getPubdate(), "dd MMM yyyy HH:mm:ss",  new Locale(AppManager.getLocaleManager().getCurrentServerLang())));
					rssText.setText(Html.fromHtml(item.getDesc()));
					rssText.setMovementMethod(LinkMovementMethod.getInstance());
					
					if(parentActivity != null){
						parentActivity.setReadNews(getPageNumber());
					}
									
				break;
				case ENPS_NORMALL:
					htmlDownloadTasks.execute();	
					
				break;
			default:
				break;
			}
		} catch (NumberFormatException e) {
			LogManager.LogEA(className,ViewUtils.getErrorMessage(e));
		} catch (Exception e) {
			LogManager.LogEA(className,ViewUtils.getErrorMessage(e));
		}
	}

	private void setState(NewsPageState newState) {
		this.newsPageState = newState;
		switch (newState) {
			case ENPS_NORMALL:
				this.rssView.setVisibility(View.GONE);
				break;
			case ENPS_RSS:
				this.rssView.setVisibility(View.VISIBLE);
				break;
			case ENPS_LOADING:
				this.rssView.setVisibility(View.GONE);
				break;
			default:
				this.rssView.setVisibility(View.GONE);
		}
	}
	
	public static NewsPage create(int pageNumber,
			com.icebergteam.warfacewidget.news.data.NewsItem item, NewsActivity parent) {
		NewsPage fragment = new NewsPage();
		Bundle args = new Bundle();
		args.putInt(NewsPage.ARG_NUMBER_PAGE, pageNumber);
		fragment.setArguments(args);
		fragment.setNewsItem(item);
		parentActivity = parent; 
		return fragment;
	}
	
	/* 1 param - true/false cache
	 * 2 param - true/false manual update 
	 */
	public class HtmlDownloadTask extends Task{
		boolean validNewsHtml = false;
		private HttpGet request;
		Document doc;
		String noPreviewSrc = "http://i.imgur.com/VD8WAZG.png";
		private boolean isCacheWikiHtml;
		private boolean isUpdateWikiHtml;
		private String fullHtml = null;
		
		public HtmlDownloadTask(boolean cache, boolean update, TaskProgress message, IHandleMessage _handleError, IProgressTracker _progressTracker) {
			super(message, _handleError, _progressTracker);
			setCacheWikiHtml(cache);
			setUpdateWikiHtml(update);
		}
		
		private boolean isCacheWikiHtml() {
			return isCacheWikiHtml;
		}
		
		private void setCacheWikiHtml(boolean isCacheWikiHtml) {
			this.isCacheWikiHtml = isCacheWikiHtml;
		}
		
		private boolean isUpdateWikiHtml() {
			return isUpdateWikiHtml;
		}
		
		private void setUpdateWikiHtml(boolean isUpdateWikiHtml) {
			this.isUpdateWikiHtml = isUpdateWikiHtml;
		}
		
		private String getClearNewsHtml(String html, String urlBase, boolean cache) throws Exception{
			doc = Jsoup.parse(html);
			
			/*remove tags by src or href attributess*/
			ArrayList<String> listRemoveBlocksBySrcHref = new ArrayList<String>();
			listRemoveBlocksBySrcHref.add("addthis.com");
			listRemoveBlocksBySrcHref.add("lightbox");
			listRemoveBlocksBySrcHref.add("odkl_share");
			listRemoveBlocksBySrcHref.add("mr_users_login_box_helper");

			for(String srcHref: listRemoveBlocksBySrcHref){
				doc.select("[src*=" + srcHref + "], [href*=" + srcHref + "]").remove();
			}
			
			String path;
			
			if(urlBase == null){
				path = WidgetProvider.NEWS_PATH;
			}
			else{
				path = urlBase;
				File news = new File(path);
				if(!news.exists()){
					news.mkdirs();
				}
			}
			
			/*cut div.l-content*/
			Elements content = doc.select("div#block_center").clone();

			if (!content.isEmpty()) {
				Element body = doc.body();
				
				content.attr(
						"style",
						"background: transparent; width:100%; float : none; padding: 0; overflow:hidden; min-height:100%; ");
			
				content.select(">*, table.pluginlike").not(".blockcontent").remove();
				
				Elements blockcontent = content.select("div.blockcontent");
				blockcontent.attr("style", "margin: 0 auto; background:0; padding:0; min-height:0;");

				blockcontent.select("div.meta, div.hr").remove();
				
				Element htmlElem = doc.select("html").first();
				htmlElem.attr("style",
						"background:none;  min-width:100%; margin-top:0;");
				
				
				
				body.select(">*").remove();
				body.attr("style",
						"background:none;  font-size:14px; padding:10px; min-height:100%;");
				body.append(content.toString());
				
				/*replace object to link with prev img*/
				Elements objects = doc.select("object, iframe");

						
				for (Element object : objects) {
					/*holder for video block*/
					Element holder = doc.createElement("div");
					holder.attr("style", "text-align:center;");
					holder.attr("class", "video");
					
					/*label video*/
					Element span = holder.appendElement("span");
					span.text("Click on the thumbnail to play video");
					span.attr("style","color:red; width: 100%; display:block");
				
					/*link to youtube video*/
					Element link = holder.appendElement("a");
					link.attr("class", "video-link");
					link.attr("style" ,"display:inline-block; position : relative;");
					link.attr("href", object.attr("data"));
				
					
					
					/*img prev video*/
					Element imgPrev = link.appendElement("img");
					imgPrev.attr("class", "video-prev");
					imgPrev.attr("style", "display:block;");
					
								
					String youtubeUrl="";
					if((youtubeUrl = YouTubeVideoPlayerActivity.getYoutubeUrl(object,true))!= null){
						LogManager.LogVA(className, youtubeUrl);	
													
						String src = YouTubeVideoPlayerActivity.getYoutubeVideoThumbnailByUrl(youtubeUrl);
						
						if(src == null){
							src = noPreviewSrc;
						}
						imgPrev.attr("src", ((cache) ? "file://": "")+ ViewUtils.getSourcePath(item.getLink(), NewsTable.TABLE_NAME, src, path, ViewUtils.TYPE_VIDEO, cache));
						link.attr("href", youtubeUrl);
					}
					else{
						imgPrev.attr("src", ((cache) ? "file://": "" )+  ViewUtils.getSourcePath(item.getLink(), NewsTable.TABLE_NAME, noPreviewSrc, path, ViewUtils.TYPE_MEDIA, cache));
						link.removeAttr("href"); 
						link.attr("onclick", String.format("javascript:window.droid.errorObjectTag()"));
					}
					object.empty();
					object.appendChild(holder);
					object.unwrap();
				}
				
				
				/*replace src, href attributes to full url*/
				Elements media = doc.select("[src], [href]");
			
				String urlStr = NetworkManager.getCustomDomainLink(item.getLink());
				for (Element src : media) {
					Pattern relativePathReg = Pattern.compile("^/");
					if (!src.attr("src").isEmpty() && !src.attr("class").equals("video-prev")){
						if(relativePathReg.matcher(src.attr("src")).find()){
							src.attr("src", urlStr + src.attr("src"));
						}
						
						String srcAtrr = src.attr("src");
						
						String fullLocalUri =  ViewUtils.getSourcePath(item.getLink(), NewsTable.TABLE_NAME, srcAtrr, path, ViewUtils.TYPE_MEDIA, cache);
						
						if(cache){
							src.attr("src", "file://"+ fullLocalUri);
							if(! src.parent().tagName().equals("a") && src.tagName().equals("img")){
								src.wrap(String.format("<a class='prev-image' style='display:inline-block;'  onclick=\"droid.zoomImage('%s');\">",src.attr("src")));
							}	
						}
					}
					else if (!src.attr("href").isEmpty() ){
						if(relativePathReg.matcher(src.attr("href")).find()){
							src.attr("href", urlStr + src.attr("href"));
						}
					}
				}
			
				html = doc.toString();
				this.validNewsHtml = true;
			}
			return html;
		}
		
		public  LinkedHashMap<String, String> decodeUrlParameters(String s)	 {
			 LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
			 try {
				List<NameValuePair> paramsList =  URLEncodedUtils.parse(new URI(s), "UTF-8");
				for(NameValuePair pair: paramsList){
					 params.put(pair.getName(), pair.getValue());
				}
			 }catch(Exception e) {
				 e.printStackTrace();
			 }
			 return params;
		 }
		
		@Override
		protected void onPreExecute() {
			NewsPage.this.runOnUi(new Runnable() {
				@Override
				public void run() {
					NewsPage.this.newsFromSite.setVisibility(View.GONE);
					NewsPage.this.updateButton.setVisibility(View.GONE);
					NewsPage.this.progressView.show();
					NewsPage.this.progressView.setProgress(-1);
				}
			});
			super.onPreExecute();
		}
		
		@Override
		protected Integer doInBackground(String... params) {
			try {
				LogManager.LogVA(className, item.getLink());

				if (isCancelled()) {
					return 1;
				}

				fullHtml = (isUpdateWikiHtml()) ? null : restoreNews();

				if (isCancelled()) {
					return 1;
				}

				if (!this.validNewsHtml || (isUpdateWikiHtml())) {
					fullHtml = updateNews(isCacheWikiHtml());
					LogManager.LogVA(className, "update news", fullHtml.substring(0, 50));
				}

				if (!this.validNewsHtml) {
					throw new Exception("not contains html div.l-content " + fullHtml.substring(0, 50));
				}
			} 
			catch (NetworkException e) {
				LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
				if (e.getStateRequest() == HttpStatus.SC_NOT_FOUND) {
					AppManager.getDatabase().getNewsTable().removeNewsItem(item.getLink());
					handleError((String) NewsPage.this.getActivity().getTitle(), getActivity().getResources().getString(R.string.not_found_current_news_removed));
				}
			} 
			catch (SQLException exc) {
				LogManager.LogEA(className, "sql error", ViewUtils.getErrorMessage(exc));
				handleError(null, null);
			}
			catch (Exception exc) {
				try {
					fullHtml = restoreNews();
					if (fullHtml == null || validNewsHtml == false) {
						throw new Exception("invalid restored html");
					}
					handleMessage((String) NewsPage.this.getActivity().getTitle(),	getActivity().getResources().getString(R.string.request_failed_restored_complete));
				}
				catch (Exception exc2) {
					LogManager.LogEA(className, "invalid get html", ViewUtils.getErrorMessage(exc2));
					handleError(null, null);
				}
			}
			return null;
		}

		public String updateNews(boolean cached) throws Exception, NetworkException, SQLException {
			request = new HttpGet(item.getLink());//*/"https://github.com/asdsad/dfg");//
			String clearHtml = getClearNewsHtml(NetworkManager.getHtml(request), null, cached);
				
			if(this.validNewsHtml && cached){
				ContentValues dataToInsert = new ContentValues();    
				dataToInsert.put(NewsTable.FIELD_URL, item.getLink());
				dataToInsert.put(NewsTable.FIELD_HTML, clearHtml);
			
				long id = AppManager.getDatabase().getNewsTable().updateOrInsert( dataToInsert);
					
				LogManager.LogVA(className, id);
			}
			return clearHtml;
		}

		public String restoreNews() throws SQLException{
			Cursor cursor = AppManager.getDatabase().getWritableDatabase().query(NewsTable.TABLE_NAME, 
					  new String[] { NewsTable.FIELD_HTML, NewsTable.FIELD_PUBDATE}, 
					  String.format("%s = '%s'", NewsTable.FIELD_URL, item.getLink()), null, null, null, null); 
			cursor.moveToFirst();
		

			String clearHtml =  cursor.getString(cursor.getColumnIndex(NewsTable.FIELD_HTML.trim()));
			this.validNewsHtml = (clearHtml == null || clearHtml != null && clearHtml.isEmpty()) ? false:true;
			
			LogManager.LogVA(className, "restore news", (clearHtml != null) ? clearHtml.substring(0, 50):"");
			return clearHtml;
		}
		public void abort(){
			if(request != null){
				request.abort();
			}
		}

		@Override
		public Object[] getOnCompleteParams() {
			return new Object[] {fullHtml, validNewsHtml } ;
		}
	};
	
	public static void errorDialog(String message, String positiveStr, OnClickListener positiveLis, String negativrStr, OnClickListener negativeLis, Context ctx){
		LogManager.LogV(className, LogManager.getExecuteMethodName(), message);

		new AlertDialog.Builder(ctx)
	      .setIcon(android.R.drawable.ic_dialog_alert)
	      .setTitle(R.string.news_activity_title)
	      .setMessage(message)
	      .setPositiveButton(positiveStr, positiveLis)
	      .setNegativeButton(negativrStr, negativeLis)
	      .show();
	}
	/* class for js injections */
	class JIFace {
		public void update() {
			NewsPage.this.update();
		}
		
		public void playYoutubeVideo(String id){
			LogManager.LogV(className, LogManager.getExecuteMethodName(), id);
			YouTubeVideoPlayerActivity.initById(id, NewsPage.this.getActivity());
		}
		
		public void playTwitchVideo(final String url){
			LogManager.LogV(className, LogManager.getExecuteMethodName(), url);
			TwitchTVVideoPlayerActivity.initByUrl(url, NewsPage.this.getActivity());
		}
		
		public void errorObjectTag(){
			LogManager.LogV(className, LogManager.getExecuteMethodName());

			errorDialog(NewsPage.this.getActivity().getString(R.string.news_page_error_object_tag), getActivity().getString(android.R.string.ok) , null, null, null, NewsPage.this.getActivity());
		}
		
		public void zoomImage(String uri){
			LogManager.LogV(className, LogManager.getExecuteMethodName());

			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse(uri), "image/*");
			startActivity(intent);
		}
		
		
	}
	
	@Override
	public void handleMessage(String title, final String string) {
		runOnUi(new Runnable() {
			@Override
			public void run() {
				if(string != null){
					Toast.makeText(NewsPage.this.getActivity(), string, Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	@Override
	public void handleError(final String title, final String string) {
		runOnUi(new Runnable() {
			@Override
			public void run() {
				NewsPage.this.progressView.hide();
				NewsPage.this.newsFromSite.loadUrl("file:///android_asset/news/404.html");
				handleMessage(title, string);
			}
		});
	}

	@Override
	public void onProgress(TaskProgress message) {
	}

	@Override
	public void onComplete(String className, Object... params) {
		final String fullHtml = (String) ((params!= null && params.length >0 )? params[0]: null);
		boolean isValidHtml = (Boolean) ((params!= null && params.length > 1 )? params[1]: null);
		if(fullHtml != null && isValidHtml){
			NewsPage.this.runOnUi(new Runnable() {
				@Override
				public void run() {
					NewsPage.this.newsFromSite.loadDataWithBaseURL("", fullHtml, "text/html", "UTF-8", "");
				}
	      });
		}
	}

	@Override
	public void onCanceled(String className, Object... params) {
	};
	
	void runOnUi(Runnable task){
		if(NewsPage.this.getActivity() != null){
			NewsPage.this.getActivity().runOnUiThread(task);
		}
	}
}